<?php
namespace org\kahikai\database\mysql;

use org\kahikai\database\AliasDao;

require_once dirname(__FILE__) . '/../GeneDao.php';
require_once dirname(__FILE__) . '/KahikaiMysql.php';
require_once dirname(__FILE__) . '/../../domain/Gene.php';

use org\kahikai\database\GeneDao;
use org\kahikai\domain\Gene;

/**
 * 
 * @author ch4mp
 *
 */
class MysqlGeneDao implements GeneDao {
	private $aliasDao;
	
	public function __construct(AliasDao $anAliasDao) {
		$this->aliasDao = $anAliasDao;
	}
	
	/**
	 *
	 * @return an array with all Genes
	 */
	public function getAll() {
		$genes = array();
		
		$result = KahikaiMysql::query('SELECT DISTINCT g.id, g.name, sg.species_id FROM GENE g, SPECIES_GENE_DEVELOPMENT_STEP sg WHERE g.id = sg.gene_id');
		while ($record = $result->fetch_assoc()) {
			if(!array_key_exists($record['species_id'], $genes)) {
				$genes[$record['species_id']] = array();
			}
			$genes[$record['species_id']][$record['id']] = new Gene($record['id'], $record['name'], $this->aliasDao->getByGeneId($record['id']));
		}
		$result->close();
		
		return $genes;
	}
	
	/**
	 *
	 * @param int $id a Gene id
	 * @return the Gene with provided id or null
	 */
	public function getById($id) {
		$gene = null;
		
		$result = KahikaiMysql::query("SELECT DISTINCT g.id, g.name FROM GENE g WHERE g.id=$id");
		if ($record = $result->fetch_assoc()) {
			$gene = new Gene($record['id'], $record['name'], $this->aliasDao->getByGeneId($record['id']));
		}
		$result->close();
		
		return $gene;
	}
	
	/**
	 * 
	 * @param int $speciesId a Species id
	 * @return an array with all Genes for provided Species (never null even if species id is unknown)
	 */
	public function getBySpeciesId($speciesId) {
		$genes = array();
		
		$result = KahikaiMysql::query("SELECT DISTINCT g.id, g.name FROM GENE g, SPECIES_GENE_DEVELOPMENT_STEP sg WHERE g.id=sg.gene_id AND sg.species_id=$speciesId");
		while ($record = $result->fetch_assoc()) {
			$genes[$record['id']] = new Gene($record['id'], $record['name'], $this->aliasDao->getByGeneId($record['id']));
		}
		$result->close();
		
		return $genes;
	}
}
?>